package com.jsy.mini12306.ticketsales.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsy.mini12306.common.entity.Train;
import com.jsy.mini12306.common.entity.TrainPassStation;
import com.jsy.mini12306.ticketsales.bo.DrivingPlan;
import com.jsy.mini12306.ticketsales.mapper.TrainMapper;
import com.jsy.mini12306.ticketsales.service.TrainService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;


/**
 * 车次（图中的路径）(Train)表服务实现类
 *
 * @author: SongyangJi
 * @since: 2021-09-01 12:55:07
 * @description:
 */

@Slf4j
@Service("trainService")
public class TrainServiceImpl extends ServiceImpl<TrainMapper, Train> implements TrainService {
    @Resource
    private TrainMapper trainMapper;

    // 模拟  redis 缓存
    Map<String,Object> cache = new HashMap<>();
    final String key = "allTrains";

    @Override
    public List<Train> listAllTrains() {
        if (cache.containsKey(key)) {
            return (List<Train>)(cache.get(key));
        }

        // TODO  慢sql优化 （耗时 3.0 s）
//        long l = System.currentTimeMillis();
        List<Train> trains = trainMapper.selectAllTrains();
        // 经停站点按照次序排序
        trains.forEach(train -> train.getTrainPassStations().sort(Comparator.comparingInt(TrainPassStation::getSequence)));
//        long l1 = System.currentTimeMillis();
//        System.out.println((l1-l)/1000+"秒");
        cache.put(key,trains);
        return trains;
    }

    @Override
    public Train queryTrainById(int trainId) {
        Train train = trainMapper.selectTrainById(trainId);
        train.sortByStationsSequence();
        List<TrainPassStation> trainPassStations = train.getTrainPassStations();
        LocalTime departTime = trainPassStations.get(0).getDepartTime();
        // 拓展属性的设置
        trainPassStations.forEach(trainPassStation -> {
            // 设置间隔
            trainPassStation.setStayTime((int) Duration.between(
                    trainPassStation.getArrivalTime(), trainPassStation.getDepartTime()).toMinutes());
            int gap = (int) Duration.between(departTime, trainPassStation.getArrivalTime()).toMinutes();
            if (gap < 0) {
                gap += 24*60;
            }
            // 设置总时间
            trainPassStation.setTotalTime(gap);
        });
        return train;
    }

    @Override
    public Train queryTrainByTrainName(String name) {
        Train train = trainMapper.selectOne(new QueryWrapper<Train>().eq("train_name", name));
        if (train!=null) {
            return this.queryTrainById(train.getTrainId());
        }
        return null;
    }
}

